<template>
  <div class="block">
    <div id="app">
      <div class="search-container">
        <div class="search-box">
          <div class="label">内容1</div>
          <el-input v-model="searchName" placeholder="请输入搜索内容"></el-input>
        </div>
        <div class="search-box">
          <div class="label">内容2</div>
          <el-input v-model="searchDesc" placeholder="请输入搜索内容"></el-input>
        </div>
        <div class="search-box">
          <div class="label">地址</div>
          <el-input v-model="searchAdd" placeholder="请输入搜索内容"></el-input>
        </div>
        <el-button type="danger" class="button primary" @click="loadData">搜索</el-button>
        <el-button type="danger" class="button1 primary" @click="dialogVisible = true">新增</el-button>
      </div>
    </div>

    <div>
      <el-dialog class="add" title="新增信息" :visible.sync="dialogVisible">
        <el-form :model="form" :rules="rules" ref="form" label-width="70px">
          <el-form-item label="标题" prop="title">
            <el-input style="width: 400px;" type="textarea" v-model="form.title"></el-input>
          </el-form-item>

          <el-form-item label="内容1" prop="content1">
            <el-input style="width: 400px;" type="textarea" v-model="form.content1"></el-input>
          </el-form-item>
          <el-form-item label="内容2" prop="content2">
            <el-input style="width: 400px;" type="textarea" v-model="form.content2"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input style="width: 400px;" type="textarea" v-model="form.phone"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input style="width: 400px;" type="textarea" v-model="form.email"></el-input>
          </el-form-item>
          <el-form-item label="地址" prop="address">
            <el-input style="width: 400px;" type="textarea" v-model="form.address"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <el-table :data="comtableData" show-header >
      <el-table-column prop="title" width="120px" label="标题">
      </el-table-column>
      <el-table-column prop="content1"  width="300px"  label="内容1">
      </el-table-column>
      <el-table-column prop="content2" width="200px"  label="内容2">
      </el-table-column>
      <el-table-column prop="image" label="图片">
        <template slot-scope="scope">
          <img :src="scope.row.image" style="width: 300px;height:200px" />
        </template>
      </el-table-column>
      <el-table-column prop="phone" width="120px" label="电话">
      </el-table-column>
      <el-table-column prop="email" width="140px" label="邮箱">
      </el-table-column>
      <el-table-column prop="address" width="150px" label="地址">
      </el-table-column>
      <el-table-column prop="weimg" label="公众号">
        <template slot-scope="scope">
          <img :src="scope.row.weimg" style="width: 100px;height:100px" />
        </template>
      </el-table-column>
      <el-table-column width="150px" label="操作">
        <template slot-scope="scope">
          <el-button size="small" type="danger" @click="handleEdit(scope.row)">修改</el-button>
          <div style="margin-top:10px">
            <el-button size="small" type="danger" @click="deletehandleEdit(scope.row)">删除</el-button>
          </div>
          <el-upload class="upload-demo" ref="uploadImg" action="api/info/upload/weimg" :headers="headers"
            :data="uploadParams" accept="image/jpg,image/jpeg" :on-error="handleError" :limit="limitNum"
            :on-exceed="handleExceed" :on-success="handleSuccess1" :before-upload="handleBeforeUpload"
            style="margin-top:10px">
            <el-button size="small" type="danger" @click="handleUpload(scope.row)">公众号</el-button>
          </el-upload>
          <el-upload class="upload-demo" ref="uploadImg" action="api/info/upload" :headers="headers"
            :data="uploadParams" accept="image/jpg,image/jpeg" :on-error="handleError" :limit="limitNum"
            :on-exceed="handleExceed" :on-success="handleSuccess1" :before-upload="handleBeforeUpload"
            style="margin-top:10px">
            <el-button size="small" type="danger" @click="handleUpload(scope.row)">图片上传</el-button>
          </el-upload>
          <!-- :file-list="fileList" -->
        </template>
      </el-table-column>
    </el-table>

    <el-dialog label="编辑信息" :visible.sync="eddialogVisible">
      <el-form :model="editForm" :rules="rules" ref="editForm" label-width="70px">
        <el-form-item label="标题" prop="title">
          <el-input style="width: 400px;" type="textarea" v-model="editForm.title"></el-input>
        </el-form-item>
        <el-form-item label="内容1" prop="content1">
            <el-input style="width: 400px;" type="textarea" v-model="editForm.content1"></el-input>
          </el-form-item>
          <el-form-item label="内容2" prop="content2">
            <el-input style="width: 400px;" type="textarea" v-model="editForm.content2"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input style="width: 400px;" type="textarea" v-model="editForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input style="width: 400px;" type="textarea" v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="地址" prop="address">
            <el-input style="width: 400px;" type="textarea" v-model="editForm.address"></el-input>
          </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="eddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>


      </div>
    </el-dialog>


  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'App',
  inject: ['reload'],
  data() {
    return {
      headers: {
        'token': 'Bearer initial'
      },
      uploadParams: {
        id: null
      },
      limitNum: 1,
      searchName: '',
      searchDesc: '',
      searchAdd:'',
      dateRange: ['', ''],
      selectedOption: '',
      comtableData: [],
      search: '',
      dialogVisible: false,
      eddialogVisible: false,
      deleteTask: false,
      form: {
        title: '',
        content1: '',
        content2: '',
        phone: '',
        email: '',
        address: '',
        weimg: '',
        image: this.selectedFile

      },
      editForm: {},
      rules: {
        title: [
          { required: true, message: '请输入项目名', trigger: 'blur' }
        ],
        content1: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ],
        content2: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入电话', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入地址', trigger: 'blur' }
        ],
      
      }

    }

  },
  created() {
    this.loadData();
    this.headers['token'] = `Bearer ${this.$getToken()}`;
  },

  methods: {
    loadData() {
      const query = {
        pageNo: this.page,
        pageSize: this.pageSize,
        content1: this.searchName,
        content2: this.searchDesc,
        address: this.searchAdd
      };
      axios.get(`api/info/page`, { params: query }).then((res) => {
        console.log(res.data.list);
        const convertedList = res.data.list.map(item => {
          return {
            ...item,
          };
        });
        this.comtableData = convertedList
        this.total = res.data.total
      }).catch((error) => {
        console.error(error);
        this.$message.error('错误')
      });
    },
    submitForm() {
      if (!this.form.title) {
        this.$message.error('项目名不能为空');
        return;
      }
      // 检查 title 字段是否为空
      if (!this.form.content1) {
        this.$message.error('内容不能为空');
        return;
      }
      axios.post(`api/info/add`, this.form).then((res) => {
        console.log(res);
        if (res.status == '200') {
          this.dialogVisible = false
          this.$message.success('新增成功')
          this.reload()
        } else {
          console.log('error submit!!')
          return false
        }
      })


    },


    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(() => {
          done();
        })
        .catch(() => { });
    },
    cancelDelete() {
      this.deleteTask = false;
    },

    handleEdit(row) {
      this.editForm = { ...row }; // 创建编辑表单的数据副本
      this.eddialogVisible = true; // 显示对话框


      // this.selectedFile = null;
    },
    saveEdit() {
      axios.put(`api/info/update`, this.editForm).then((res) => {

        console.log(res);
        // 在这里处理保存编辑后的数据
        console.log('保存编辑后的数据:', this.editForm);
        if (res.status == '200') {
          this.eddialogVisible = false; // 关闭对话框
          this.$message.success('修改信息成功')
          this.reload()
        } else {
          this.$message.success('修改信息失败，请联系开发者')
          return false
        }
      });
    },

    deletehandleEdit(row) {
      if (row.id != null) {
        let id = row.id;
        if (id == null) {
          this.$message.error('请选择需要删除的成员。')
        } else {
          axios.delete(`api/info/delete/${id}`).then((res) => {
            console.log(res);
            this.$message.success('删除成功')
            this.reload()
          })
        }
      } else {
        this.$message.error('请先选择需要删除的成员。');
      }
      console.log(row);
      console.log(row.taskid);
    },

    // 照片文件超出个数限制时的钩子
    handleExceed(files, fileList) {
      this.$notify.warning({
        title: '警告',
        message: `只能选择 ${this.limitNum} 个文件，当前共选择了 ${files.length + fileList.length} 个`
      })
    },
    // 上传照片文件之前的钩子
    handleBeforeUpload(file) {
      console.log(file.type)
      if (!(file.type === 'image/jpg' || file.type === 'image/jpeg')) {
        this.$notify.warning({
          title: '警告',
          message: '请上传格式为image/jpg的图片'
        })
      }
      // const size = file.size / 1024 / 1024
      // if (size > 1) {
      //   this.$notify.warning({
      //     title: '警告',
      //     message: '图片大小必须小于1M'
      //   })
      // }
    },
    handleSuccess1() {
      this.dialogImageUrl = ''
      this.reload()
      this.$notify({
        title: '恭喜',
        message: '添加图片成功',
        type: 'success',
        duration: 5000
      })
    },
    // 上传图片
    handleUpload(row) {
      this.uploadParams.id = row.id
      console.log(row);
      const token = localStorage.getItem('token'); // 确保这个函数返回有效的token
      this.headers = {
        'Authorization': `Bearer ${token}`
      };
    },

  }
}
</script>

<style>
.search-container {
  margin-bottom: 20px;
}

#app {
  /* font-family: Avenir, Helvetica, Arial, sans-serif; */
  font-family: PingFangSC-Medium;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  background-color: #fff;
  color: #606266;
  border-radius: 20px;
}

.search-container {

  display: flex;
  justify-content: center;
  align-items: center;


}

.search-container>div {
  margin-right: 70px;
  margin-bottom: 20px;
}

.label {
  margin-top: 30px;
  text-align: left;
  margin-bottom: 20px;
  font-weight: bold;

}

.button {
  font-family: PingFangSC-Medium;
  width: 90px;
  height: 50px;
  background: #f27657;
  border-radius: 20px;
}

.button1 {
  font-family: PingFangSC-Medium;
  width: 90px;
  height: 50px;
  background: #f3a895;
  border-radius: 20px;
}

.button:hover {
  background: #F16440;
  border: 0;
}
</style>